﻿using HookupAppForm.Dto;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HookupAppForm
{
    public partial class FormRole : Form
    {
        private string url = "api/services/app/Role/";
        private RoleDto Item { get; set; }
        private APIClient Client { get; set; }
        public FormRole(RoleDto item, APIClient _client)
        {
            InitializeComponent();
            Item = item;
            Client = _client;
        }

        private void FormRole_Load(object sender, EventArgs e)
        {
            GetAllPermissions();
            LoadData();
            saveToolStripButton.Enabled = Item != null;
            delToolStripButton.Enabled = Item != null;
        }
        private void LoadData()
        {
            string act = string.Format(url + "GetAll");
            var result = Client.Get(act);
            if (Utils.ExceptionHandler(result) == null)
            {
                ItemsDto<RoleDto> res = JsonConvert.DeserializeObject<ItemsDto<RoleDto>>(result);
                dataGridViewM.DataSource = res.result.items;
                FromSetting[] fromSettings = new FromSetting[3];
                fromSettings[0] = new FromSetting { FieldDisplay = "编号", FieldWidth = 60 };
                fromSettings[1] = new FromSetting { FieldDisplay = "角色名" };
                fromSettings[2] = new FromSetting { FieldDisplay = "显示名" };
                Utils.SetHeader(dataGridViewM, fromSettings);
            }
        }
        private void GetAllPermissions()
        {
            string act = string.Format(url + "GetAllPermissions");
            var result = Client.Get(act);
            if (Utils.ExceptionHandler(result) == null)
            {
                ItemsDto<PermissionDto> res = JsonConvert.DeserializeObject<ItemsDto<PermissionDto>>(result);
                dataGridViewM.DataSource = res.result.items;
                foreach (var item in res.result.items)
                {
                    cListBoxPermissions.Items.Add(item.Name, false);
                }
            }

        }

        private void NewToolStripButton_Click(object sender, EventArgs e)
        {
            ResetForm();
            saveToolStripButton.Enabled = true;
        }

        private void SaveToolStripButton_Click(object sender, EventArgs e)
        {
            string act = Item == null ? "Create" : "Update";
            string result = string.Empty;
            List<string> selectRoles = new List<string>();
            for (int i = 0; i < cListBoxPermissions.Items.Count; i++)
            {
                if (cListBoxPermissions.GetItemChecked(i))
                {
                    selectRoles.Add(cListBoxPermissions.Items[i].ToString());
                }
            }

            if (Item != null)
            {
                Item.Name = textBoxName.Text;
                Item.GrantedPermissions = selectRoles;
                Item.DisplayName = textBoxDisplayName.Text;
                string jsons = JsonConvert.SerializeObject(Item);
                result = Client.Put(url + act, jsons);
            }
            else
            {
                CreateRoleDto dto = new CreateRoleDto();
                dto.Name = textBoxName.Text;
                dto.GrantedPermissions = selectRoles;
                dto.DisplayName = textBoxDisplayName.Text;
                string jsons = JsonConvert.SerializeObject(dto);
                result = Client.Post(url + act, jsons);
            }
            if (Utils.ExceptionHandler(result) == null)
            {
                Utils.SysMsg("保存成功！");
                var resp = Utils.SuccessHandler(result);
                Item = JsonConvert.DeserializeObject<RoleDto>(resp.ToString());
                LoadData();
            }
        }


        private void DelToolStripButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定删除？", "系统", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                if (Item != null)
                {
                    string act = string.Format(url + "Delete?Id={0}", Item.Id);
                    string result = Client.Delete(act);
                    if (Utils.ExceptionHandler(result) == null)
                    {
                        ResetForm();
                        LoadData();
                        saveToolStripButton.Enabled = false;
                    }
                }
            }
        }

        private void ResetForm()
        {
            if (Item != null)
            {
                textBoxName.Text = "";
                textBoxDisplayName.Text = "";
                Item = null;
            }
        }

        private void DataGridViewM_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            Item = dataGridViewM.CurrentRow.DataBoundItem as RoleDto;
            if (Item != null)
            {
                textBoxName.Text = Item.Name;
                textBoxDisplayName.Text = Item.DisplayName;

                for (int i = 0; i < cListBoxPermissions.Items.Count; i++)
                {
                    bool chk = Item.GrantedPermissions.ToArray().Contains(cListBoxPermissions.Items[i].ToString());
                    cListBoxPermissions.SetItemChecked(i, chk);
                }
                saveToolStripButton.Enabled = true;
                delToolStripButton.Enabled = true;
            }
        }
    }
}
